import re

"""
将 html 转换成 django 模版格式
"""


def old2new(file_name, path_new, path_old):
    file_name_new = file_name
    with open(path_old + file_name, 'r') as f:
        with open(path_new + file_name_new, 'w') as w:
            w.write("{% load static %}\n")
            for line in f.readlines():
                if 'link' in line:
                    href = re.match(r'(.*)href="(?P<href>.*?)"(.*)', line)['href']
                    _href = "{% static '" + href + "' %}"
                    line = line.replace(href, _href)
                elif "img" in line and "src" in line:
                    href = re.match(r'(.*)src="(?P<href>.*?)"(.*)', line)['href']
                    _href = "{% static '" + href + "' %}"
                    line = line.replace(href, _href)
                elif "script" in line and "src" in line:
                    href = re.match(r'(.*)src="(?P<href>.*?)"(.*)', line)['href']
                    _href = "{% static '" + href + "' %}"
                    line = line.replace(href, _href)
                w.write(line)


if __name__ == '__main__':
    _path_new = '/Users/weicai/projects/public_dataset/shop/templates/admin/'
    _path_old = '/Users/weicai/projects/public_dataset/admin/'
    old2new('pages-login.html', _path_new, _path_old)
